package com.lcf.app.redis.component;

import com.alibaba.fastjson.JSON;
import com.lcf.app.redis.model.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Set;

/**
 * @author ChenFei
 * @date 2021/10/29
 */
@Slf4j
@Component
public class RedisDemo {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @PostConstruct
    public void test() {

        redisTemplate.opsForValue();//操作字符串
        redisTemplate.opsForHash();//操作hash
        redisTemplate.opsForList();//操作list
        redisTemplate.opsForSet();//操作set
        redisTemplate.opsForZSet();//操作有序set

        log.info("------------------>存入");
        stringRedisTemplate.opsForValue().set("key1", "key1-value");
        String key1 = stringRedisTemplate.opsForValue().get("key1");
        log.info("------------------>取出:{}", key1);

        log.info("------------------>存入");
        redisTemplate.opsForValue().set("key2", new User().setAge(18).setBirthday(LocalDateTime.now()).setName("ChenFei"));
        //这个User必须实现Serializable接口，不然的话取出数据会报序列化错误
        User key2 = (User) redisTemplate.opsForValue().get("key2");
        log.info("------------------>取出:{}", JSON.toJSONString(key2));

        log.info("------------------>存入");
        redisTemplate.opsForSet().add("key3", new User().setName("ChenFei"), new User().setAge(18));
        Set<User> key3 = (Set) redisTemplate.opsForSet().members("key3");
        log.info("------------------>取出:{}", JSON.toJSONString(key3));

        Set<String> keys = stringRedisTemplate.keys("*");
        log.info("keys:{}", keys.toString());

    }

}
